package com.forum.demo.controller;

import com.forum.demo.common.AppResult;
import com.forum.demo.common.ResultCode;
import com.forum.demo.config.AppConfig;
import com.forum.demo.model.UserInfo;
import com.forum.demo.services.impl.UserServiceImpl;
import com.forum.demo.utils.checkFailUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    // 定义头像路径
    @Value("${file.upload-dir}")
    private String uploadDir;

    // 注册
    @PostMapping("/register")
    public AppResult register(@NonNull String username,
                              @NonNull String nickname,
                              @NonNull String password,
                              @NonNull String passwordRepeat) {
        // 1. 检验密码与与确认密码是否相同
        if (!password.equals(passwordRepeat)) {
            checkFailUtils.checkFail(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        UserInfo user = new UserInfo();
        user.setUsername(username);
        user.setPassword(password);
        user.setNickname(nickname);
        userService.createNormalUser(user);
        return AppResult.success();
    }
    // 登录
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request, @NonNull String username, @NonNull String password) {
        UserInfo user = userService.login(username, password);
        if (user == null || user.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        HttpSession session1 = request.getSession(false);
        // 如果用户还未登录就存在session就该先销毁这个session
        if (session1 != null) {
            session1.invalidate();
        }
        // 如果登录成功把User对象设置到Session作用域中
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION, user);
        return AppResult.success();
    }

    @GetMapping("/info")
    public AppResult<UserInfo> getUserInfo(HttpServletRequest request, @RequestParam(value = "id", required = false) Long id) {
        UserInfo user = null;
        // 1. 判断Id是否为空
        if (id == null) {
            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute(AppConfig.USER_SESSION) == null) {
                checkFailUtils.checkFail(ResultCode.FAILED_FORBIDDEN);
            }
            user = (UserInfo) session.getAttribute(AppConfig.USER_SESSION);
            id = user.getId();
        }
        UserInfo updateUser = userService.selectById(id);
        if (updateUser == null) {
            checkFailUtils.checkFail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(updateUser);
    }

    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        return AppResult.success();
    }

    @PostMapping("/modifyInfo")
    public AppResult<UserInfo> modifyInfo (HttpServletRequest request,
                                 @RequestParam(value = "username",required = false) String username,
                                 @RequestParam(value = "nickname",required = false) String nickname,
                                 @RequestParam(value = "gender",required = false) Byte gender,
                                 @RequestParam(value = "email",required = false) String email,
                                 @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                 @RequestParam(value = "remark",required = false) String remark) {
        HttpSession session = request.getSession(false);
        UserInfo user = (UserInfo) session.getAttribute(AppConfig.USER_SESSION);
        UserInfo updateUser = new UserInfo();
        updateUser.setId(user.getId()); // 用户Id
        updateUser.setUsername(username); // 用户名
        updateUser.setNickname(nickname); // 昵称
        updateUser.setGender(gender); // 性别
        updateUser.setEmail(email); // 邮箱
        updateUser.setPhoneNum(phoneNum); // 电话
        updateUser.setRemark(remark); // 个人简介
        userService.modifyInfo(updateUser);
        // 这里之前有个错误,需要重新去数据库查询更新后的用户信息，现在的updateUser有些值是空的不能直接返回
        UserInfo retUser = userService.selectById(user.getId());
        //  把最新的用户信息设置到session中
        session.setAttribute(AppConfig.USER_SESSION, retUser);
        return AppResult.success(retUser);
    }

    @PostMapping("/modifyPwd")
    public AppResult modifyPassword (HttpServletRequest request,
                                      @NonNull String oldPassword,
                                      @NonNull String newPassword,
                                      @NonNull String passwordRepeat) {
        if (!newPassword.equals(passwordRepeat)) {
            checkFailUtils.checkFail(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 2. 获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        UserInfo user = (UserInfo) session.getAttribute(AppConfig.USER_SESSION);
        // 3. 调用Service
        userService.modifyPassword(user.getId(), newPassword, oldPassword);
        // 4. 销毁session
        if (session != null) {
            session.invalidate();
        }
        // 5. 返回结果
        return AppResult.success();
    }

    @RequestMapping("/saveImage")
    public AppResult savaImage(HttpServletRequest request ,@RequestParam("file") MultipartFile file) throws IOException {
        // 获取用户信息
        HttpSession session = request.getSession(false);
        UserInfo user = (UserInfo) session.getAttribute(AppConfig.USER_SESSION);
        // 找到项目的根目录
        String projectRoot = System.getProperty("user.dir");
        String dir = Paths.get(projectRoot, uploadDir).toString();
        String originalFilename = System.currentTimeMillis() + file.getOriginalFilename();
        // 定义目标文件路径
        File destFile = new File(dir +"/"+ originalFilename);
        file.transferTo(destFile);
        System.out.println(destFile);
        System.out.println(originalFilename);
        UserInfo updateUser = new UserInfo();
        // 转化成相对路径存储 ./images/xxx.png
        updateUser.setAvatarUrl("./images/" + originalFilename);
        updateUser.setId(user.getId());
        userService.modifyInfo(updateUser);
        return AppResult.success();
    }

}
